package com.woniuxy.springboot.mybatis.controller;

import com.woniuxy.springboot.mybatis.bean.R;
import com.woniuxy.springboot.mybatis.pojo.User;
import com.woniuxy.springboot.mybatis.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/users")
    @CrossOrigin
    @ApiOperation("查询所有用户")
    public R getAllUsers(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String token = req.getHeader("token");
        System.out.println(token);

        List<User> users = userService.selectAllUsers();
        //模拟异常
//        int a=10/0;
//        if(users!=null && users.size()>0){
//           return R.ok().data("users",users);
//        }else {
//            throw new MyException(202,"员工集合为空");
//        }

        if (users != null) {
            if (users.size() > 0) {
                return R.ok().data("users", users).data("token", 888888);
            } else {
                return R.error().message("暂无数据");
            }
        } else {
            return R.error().message("集合对象为null");
        }
    }

    @GetMapping("/users/{uid}")
    @CrossOrigin
    @ApiOperation("按照id查询")
    public R getUserByUid(@ApiParam(value = "员工编号", required = true, name = "uid") @PathVariable Integer uid) {
        User user = userService.selectUserByUid(uid);
        if (user != null) {
            return R.ok().data("user", user);
        } else {
            return R.error();
        }
    }
//    @GetMapping("/select")
//    @CrossOrigin
//    @ApiOperation("按照id查询")
//    public R getUserByUid(@ApiParam(value = "员工编号", required = true, name = "uid")  Integer uid) {
//        User user = userService.selectUserByUid(uid);
//        if (user != null) {
//            return R.ok().data("user", user);
//        } else {
//            return R.error();
//        }
//    }

    @PostMapping("/users")
    @ApiOperation("新增")
    public R insertUser(User user) {
        int res = userService.insertUser(user);
        if (res > 0) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @PostMapping("/getUsersByIds")
    @ApiOperation("查询根据id集合")
    @CrossOrigin
    public R getUsersByIds(@RequestParam("ids") List<Integer> ids) {
        List<User> users = userService.selectUserByUids(ids);
        if (!CollectionUtils.isEmpty(users)) {
            return R.ok().data("users",users);
        } else {
            return R.error();
        }
    }
}
